package listbyorder.access101_200.test134;

/**
 * @author code_yc
 * @version 1.0
 * @date 2020/6/11 10:25
 */
public class Solution2 {

    // 方法二： 当我一个位置不合法，直接跳到导线位置的后面开始搜索
    public int canCompleteCircuit(int[] gas, int[] cost) {
        if (gas == null || gas.length == 0) return -1;
        int len = gas.length;

        for (int i = 0; i < len; i++) {
            int j = i;
            int sum = gas[i];
            while (sum - cost[j] >= 0) {
                sum = sum - cost[j] + gas[(j + 1) % len];
                j = (j + 1) % len;
                if (j == i) {
                    return i;
                }
            }
            if (j < i) return -1;
            i = j;
        }
        return -1;
    }
}
